package com.example.shop.merchant.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.shop.common.api.ServiceReturn;
import com.example.shop.common.api.ServiceStateCode;
import com.example.shop.mapper.UserMapper;
import com.example.shop.merchant.service.ChatService;
import com.example.shop.pojo.Merchant;
import com.example.shop.pojo.User;
import com.example.shop.rabbitmq.component.UserMessageComponent;
import com.example.shop.rabbitmq.dto.ChatMessage;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ChatServiceImpl implements ChatService {

    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    UserMapper userMapper;

    @Override
    public ServiceReturn<Boolean> send(Merchant merchant, ChatMessage chatMessage) {

        //保证发送的商家是当前登录的商家
        //这是由于Long类型对象的==是比较2个地址，而equals被重写了为value == ((Long)obj).longValue(),所以是进行值的比较
        if(!merchant.getMerchantId().equals(chatMessage.getMerchantId())){
            return new ServiceReturn(ServiceStateCode.No_PERMISSION_TO_SEND,false);
        }
        //校验该用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",chatMessage.getUserId());
        boolean exists = userMapper.exists(queryWrapper);
        if(!exists){
            return new ServiceReturn(ServiceStateCode.NO_EXIST_USER,false);
        }

        //消息发送前的消息处理
        MessagePostProcessor messagePostProcessor=(msg)->{
            MessageProperties messageProperties = msg.getMessageProperties();
            //设置消息类型，默认application/octet-stream
            //设置为json字符串类型
            messageProperties.setContentType(MessageProperties.CONTENT_TYPE_JSON);
            return msg;
        };
        //前端显示，则自己发送的，则显示靠自己那一边
        //队列名,因为是用户发送调用的接口，所以发送者就是userId，而接收者接收商家id
        String routing = String.valueOf(chatMessage.getUserId());
        //将消息发送指定的商家队列
        rabbitTemplate.convertAndSend(UserMessageComponent.MSG_EXCHANGE,routing,chatMessage,messagePostProcessor);
        return new ServiceReturn(ServiceStateCode.SUCCESS,true);
    }
}
